import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'

Vue.use(VueRouter)

VueRouter.prototype.savePush = VueRouter.prototype.push
VueRouter.prototype.push = function (options, resolve, reject) {
    if (!resolve && !reject) {
        return this.savePush(options).catch(() => { })
    } else {
        return this.savePush(options, resolve, reject)
    }
}

VueRouter.prototype.saveReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function (options, resolve, reject) {
    if (!resolve && !reject) {
        return this.saveReplace(options).catch(() => { })
    } else {
        return this.saveReplace(options, resolve, reject)
    }

}

const router = new VueRouter({
    mode:'history',
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})

import store from '@/store'
//全局前置路由守卫
router.beforeEach(async (to, from, next) => {
    const { token, userInfo } = store.state.users
    //若token存在
    if (token) {
        //如果去登录页
        if (to.path === '/login') next('/')
        else {
            //如果存在用户信息
            if (userInfo.name) {
                next()
            } else {
                try {
                    //获取用户信息
                    await store.dispatch('getUserInfo')
                    next()
                } catch (error) {
                    alert('登录过期,请重新登录...')
                    store.dispatch('removeToken')
                    next('/login')
                }
            }
        }
    } else {
        const targetPath =to.path
        if(targetPath.startsWith('/trade')||targetPath.startsWith('/pay')||targetPath.startsWith('/center')){
            next('/login?redirect='+to.path)
        }
        next()
    }
})


export default router
